<template>
    <div class="wh-100% flex flex-col gap-10px overflow-scroll">
        <SearchCard :model="'customer'" />
        <n-card class="h-full" title="客户列表">
            <template #header-extra>
                <div class="flex gap-10px">
                    <n-button
                        ghost
                        size="small"
                        :focusable="false"
                        @click="handleRefreshPage"
                    >
                        <template #icon>
                            <n-icon :component="RefreshCircle" />
                        </template>
                        刷新
                    </n-button>
                    <n-button
                        ghost
                        type="info"
                        size="small"
                        :focusable="false"
                        @click="
                            customerFormvisible = true;
                            customerFormModel = 'create';
                            currentCustomer = null;
                        "
                    >
                        <template #icon>
                            <n-icon :component="Add" />
                        </template>
                        新增
                    </n-button>
                    <n-button
                        ghost
                        type="error"
                        size="small"
                        :disabled="selectedCustomers.length === 0"
                        :focusable="false"
                        @click="handleDeleteCustomer('batch')"
                    >
                        <template #icon>
                            <n-icon :component="Trash" />
                        </template>
                        批量删除
                    </n-button>
                </div>
            </template>
            <n-data-table
                :loading="loading"
                :columns="columns"
                :data="currentCustomers"
                :row-key="(row: Customer) => row.id"
                @update:checked-row-keys="(keys: DataTableColumnKey[]) => {
                    selectedCustomers = currentCustomers.filter((item) => keys.includes(item.id!));
                }
            "
            >
            </n-data-table>
            <template #footer>
                <div class="w-full flex justify-end">
                    <n-pagination
                        v-model:page="pagination.page"
                        :page-count="
                            Math.ceil(pagination.total / pagination.pageSize)
                        "
                        @update:page="handleChangePage"
                    >
                        <template #prefix>
                            <span>共 {{ pagination.total }} 条</span>
                        </template>
                    </n-pagination>
                </div>
            </template>
        </n-card>
        <n-drawer
            v-model:show="customerFormvisible"
            :width="360"
            placement="right"
        >
            <n-drawer-content>
                <template #header>
                    {{
                        customerFormModel === "create"
                            ? "新增客户"
                            : "编辑客户信息"
                    }}
                </template>
                <UserForm
                    :role="'customer'"
                    :model="customerFormModel"
                    :data="currentCustomer"
                    @submit:data="(data) => customerFormModel === 'create'
                            ? handleAddCustomer(data as Customer)
                            : handleUpdateCustomer(data as Customer | string)"
                    @update:password="handleUpdateCustomer"
                />
            </n-drawer-content>
        </n-drawer>
    </div>
</template>

<script lang="ts" setup>
import { h, ref, reactive, onMounted } from "vue";

import type { DataTableColumns, DataTableColumnKey } from "naive-ui";
import type { Customer } from "@/service/api/types/user";

import { NTag, NButton, NDivider } from "naive-ui";
import { RefreshCircle, Add, Trash } from "@vicons/ionicons5";

import {
    getCustomerCounts,
    getCustomersList,
} from "@/service/api/modules/customer";
import { addUser, updateUser, deleteUser } from "@/service/api/modules/user";

import SearchCard from "../components/search-card/index.vue";
import UserForm from "@/components/user-form/index.vue";

const loading = ref(false);
// 表格列内容
const columns: DataTableColumns<Customer> = [
    {
        type: "selection",
    },
    {
        title: "账号",
        key: "account",
        align: "center",
    },
    {
        title: "昵称",
        key: "username",
        align: "center",
    },
    {
        title: "手机号",
        key: "phone",
        align: "center",
    },
    {
        title: "公司名称",
        key: "companyName",
    },
    {
        title: "账号状态",
        key: "frozen",
        align: "center",
        render(row) {
            return h(NTag, { type: row.frozen ? "error" : "success" }, () => {
                return row.frozen ? "冻结" : "正常";
            });
        },
    },
    {
        title: "操作",
        key: "action",
        align: "center",
        width: 200,
        render(row) {
            return h("div", { class: "flex-center gap-10px" }, [
                h(
                    NButton,
                    {
                        size: "small",
                        type: "primary",
                        ghost: true,
                        onClick: () => {
                            currentCustomer.value = row;
                            customerFormvisible.value = true;
                            customerFormModel.value = "update";
                        },
                    },
                    () => {
                        return "编辑";
                    }
                ),
                h(NDivider, { vertical: true }),
                h(
                    NButton,
                    {
                        size: "small",
                        type: "error",
                        ghost: true,
                        onClick: () => {
                            currentCustomer.value = row;
                            handleDeleteCustomer("single");
                        },
                    },
                    () => {
                        return "删除";
                    }
                ),
            ]);
        },
    },
];

// 缓存数据, key为页码, value为客户数据
const customers: Map<number, Customer[]> = new Map();
// 当前页数据, 用于渲染表格
const currentCustomers = ref<Customer[]>([]);
// 选中的客户数据
const selectedCustomers = ref<Customer[]>([]);
// 当前要编辑的客户数据
const currentCustomer = ref<Customer | null>(null);

const customerFormvisible = ref(false);
const customerFormModel = ref<"create" | "update">("update");

// 分页信息
const pagination = reactive({
    page: 1,
    pageSize: 10,
    total: 0,
});

const getCustomers = async (page: number) => {
    loading.value = true;
    try {
        const res = await getCustomersList({
            page: page,
            size: pagination.pageSize,
        });
        currentCustomers.value = res;
        customers.set(pagination.page, res);
        loading.value = false;
    } catch (err) {
        window.NMessage.error((err as Error).message);
    } finally {
        loading.value = false;
    }
};

onMounted(async () => {
    try {
        pagination.total = await getCustomerCounts();
        if (pagination.total === 0) {
            return;
        }
        getCustomers(pagination.page);
    } catch (err) {
        window.NMessage.error((err as Error).message);
    } finally {
        loading.value = false;
    }
});

// 切换页码
const handleChangePage = (page: number) => {
    pagination.page = page;
    // 如果缓存中有数据，直接从缓存中获取
    if (customers.has(page)) {
        currentCustomers.value = customers.get(page)!;
        return;
    }
    // 如果缓存中没有数据，从后端获取
    getCustomers(page);
};

// 刷新当前页
const handleRefreshPage = async () => {
    pagination.page = 1;
    pagination.total = await getCustomerCounts();
    customers.clear();

    getCustomers(pagination.page);
};

const handleAddCustomer = async (data: Customer) => {
    try {
        await addUser(data);
        window.NMessage.success("新增成功");
        customerFormvisible.value = false;
        pagination.total++;
        handleRefreshPage();
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
};

const handleUpdateCustomer = async (data: Customer | string) => {
    try {
        if (typeof data === "string") {
            data = { ...currentCustomer.value, password: data } as Customer;
        }
        await updateUser(data);
        window.NMessage.success("修改成功");
        customerFormvisible.value = false;
        handleRefreshPage();
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
};

const handleDeleteCustomer = (model: "single" | "batch") => {
    window.NDialog.warning({
        title: "警告",
        content: "确定要删除选中的客户?",
        closable: false,
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: async () => {
            try {
                if (model === "single") {
                    await deleteUser([currentCustomer.value!.id!]);
                    pagination.total -= 1;
                } else {
                    let ids = selectedCustomers.value.map((item) => item.id!);
                    await deleteUser(ids);
                    pagination.total -= ids.length;
                }
                customers.clear();
                handleRefreshPage();
                window.NMessage.success("删除成功");
            } catch (err) {
                window.NMessage.error((err as Error).message);
            }
        },
    });
};
</script>

<style scoped></style>
